/**
 * Created with JetBrains WebStorm.
 * User: rekey
 * Date: 8/9/13
 * Time: 12:20
 * To change this template use File | Settings | File Templates.
 */
var config = require('../config');
var redis = require('redis');
var when = require('when');
//api https://github.com/mranney/node_redis

function createClient() {
    var client = redis.createClient(config.redis.port, config.redis.host);
    client.auth(config.redis.pass);
    return client;
}

createClient.redis = redis;

module.exports = {
    create : createClient,
    get : function(key) {
        var deferred = when.defer();
        var redisClient = createClient();
        redisClient.get(config.redis.name + '_' + key, function(err, doc) {
            if (err || !doc) {
                deferred.reject(err);
            } else {
                deferred.resolve(doc);
            }
            redisClient.end();
        });
        return deferred.promise;
    },
    set : function(key, data) {
        var deferred = when.defer();
        var redisClient = createClient();
        redisClient.expire(config.redis.name + '_' + key, 1);
        redisClient.set(config.redis.name + '_' + key, data, function(err, doc) {
            if (err) {
                deferred.reject(err);
            } else {
                deferred.resolve(doc);
            }
            redisClient.end();
        });
        return deferred.promise;
    }
};